package pfx;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Enumeration;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

import sun.misc.BASE64Encoder;

public class Pfx_get_privateKey {

	/**
	 * 使用 pfx文件 获取 私钥，
	 *  1. pfx 通过 fileUtile读取，转化为 byteArrayInputStream 
	 *  2. 用keystore来获取 条目
	 *  3. 枚举获取 别名 
	 *  4. 获取 keystore 得到 私钥
	 *  
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception{
		
		String pfxPath = "C:\\Users\\Administrator\\Desktop\\ttt\\bankside2501.pfx";
		String password = "123456";
		PrivateKey privateKey = null;
		
		privateKey = getPrivateKey(pfxPath, password);
		
		byte[] byte_privateKey = privateKey.getEncoded();
		String string_privateKey = Base64.encodeBase64String(byte_privateKey);
		System.out.println(string_privateKey);
	}
	/**
	 * 
	 * @param pfxPath
	 * @param password
	 * @return
	 * @throws Exception
	 */
	public static PrivateKey getPrivateKey(String pfxPath,String password) throws Exception{
		PrivateKey privateKey = null;
		
		// 以文件的形式读取数据，转换为字节数组的形式
		File file = new File(pfxPath);
		byte[] byte_pfx = FileUtils.readFileToByteArray(file);
		
		// 准备一个 keystore,读取 证书 条目
		KeyStore keyStore = getKeyStore(byte_pfx,password);
		
		// 枚举找到 aliases
		Enumeration<String> enum_aliases =  keyStore.aliases();
		String alia = "";
		while(enum_aliases.hasMoreElements()){
			alia = enum_aliases.nextElement();
			if(keyStore.isKeyEntry(alia)){
				privateKey = (PrivateKey) keyStore.getKey(alia, password.toCharArray());
			}
		}
		return privateKey;
	}

	private static KeyStore getKeyStore(byte[] byte_pfx, String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
		
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		keyStore.load(new ByteArrayInputStream(byte_pfx), password.toCharArray());
		return keyStore;
	}
	
	
}









